package com.hishop.common;

import com.hishop.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by hejie on 2018/2/6.
 */
public class RedisPool {
    private static JedisPool pool;
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total"));
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle"));//最大空闲状态
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle"));//最小空闲状态
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow"));//true得到的jedis实例可用
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return"));//true返回的jedis实例可用
    private static String ip= PropertiesUtil.getProperty("redis.ip");
    private static Integer port= Integer.parseInt(PropertiesUtil.getProperty("redis.port"));
    private static String password= PropertiesUtil.getProperty("redis.password");

    static{
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true); //连接耗尽时是否阻塞，false会抛异常，true阻塞直到超时
        pool=new JedisPool(config,ip,port,1000*3,password);
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(Jedis jedis){
        pool.returnResource(jedis);
    }

    public static void returnBrokenResource(Jedis jedis){
        pool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        Jedis jedis=pool.getResource();
        jedis.set("hjkey","hjvalue");
        returnResource(jedis);
        pool.destroy();//临时调用，销毁连接池
    }

}
